<template>
  <div style="border: 1px solid #ccc;">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" :mode="mode" />
    <Editor style="height: 500px; overflow-y: hidden;" v-model="html" :defaultConfig="editorConfig" :mode="mode"
      @onCreated="onCreated" @onChange="lisChange($event)" />
    <button @click="add">tianjia</button>
  </div>
</template>

<script>
import Vue from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default Vue.extend({
  components: { Editor, Toolbar },
  props: {
    /* 编辑器的内容 */
    value: {
      type: String,
      default: "",
    },
  },
  watch: {
    value: {
      handler(val) {
        if (val !== this.html) {
          console.log(111)
          this.html = val === null ? "" : val;
          if (this.editor) {
            this.html = val
          }
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      editor: null,
      html: '<div>hello</div>',
      toolbarConfig: {},
      editorConfig: { placeholder: '请输入内容...' },
      mode: 'default', // or 'simple'
    }
  },
  methods: {
    lisChange(e) {
      console.log(this.html)
      // this.html = this.html + "<span>okokok</span>"
    },
    onCreated(editor) {
      console.log(123);
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    add() {
      // const op = document.createElement("p")
      // op.innerHTML = "xiaowang"
      const node = { type: 'paragraph', children: [{ text: 'simple text' }] }
      const node2 = { type: 'paragraph',children: [{ text: 'hello' }] }
      this.editor.insertNode(node2)

    }
  },
  mounted() {
    // 模拟 ajax 请求，异步渲染编辑器
    // setTimeout(() => {
    //   this.html = '<div class="ajax">模拟 Ajax 异步设置内容 HTML</div>'
    // }, 1500)

  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  }
})
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
